package com.lotter.api.service;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lotter.common.context.YcContext;
import com.lotter.common.enumobject.PrentCheckStatus;
import com.lotter.common.exception.LotterCusException;
import com.lotter.common.util.DateUtil;
import com.lotter.common.util.LongUtil;
import com.lotter.dao.PresentCheckMapper;
import com.lotter.dao.UserAccountMapper;
import com.lotter.model.bankcard.BankCard;
import com.lotter.model.precentcheck.PresentCheck;
import com.lotter.model.user.UserAccount;


@Service
public class PresentCheckService {
	
	@Autowired
	private PresentCheckMapper presentCheckMapper ;
	
	@Autowired
	private UserAccountMapper userAccountMapper ;
	
	
	//保存提现申请
	@Transactional(rollbackFor=Exception.class)
	public Boolean insert(Map<String,String> result,
			UserAccount userAccount,Long presentamount,
			BankCard bankCard) throws LotterCusException{
		
		//提现记录
		PresentCheck presentCheck = new PresentCheck();
		presentCheck.setMobile(userAccount.getMobile());
		presentCheck.setUid(userAccount.getId());
		presentCheck.setPresentamount(presentamount);
		presentCheck.setBankaccount(bankCard.getBankcard());
		presentCheck.setBankname(bankCard.getBankName());
		presentCheck.setHoldername(bankCard.getRealname());
		presentCheck.setPstatus(PrentCheckStatus.UNPAY.getCode());
		presentCheck.setCreatedate(new Date());
		presentCheckMapper.insert(presentCheck);
		
		//presentbalance
		UserAccount userAccountNew = new UserAccount(); 
		userAccountNew.setId(userAccount.getId());
		//冻结金额  上一次冻结加上这次提现
		Long presentbalance = LongUtil.add(userAccount.getPresentbalance()==null ? 0l :userAccount.getPresentbalance(),presentamount);
		userAccountNew.setPresentbalance(presentbalance);
		Long amount =  userAccount.getAmount()==null ? 0l :userAccount.getAmount() ;
		//判断账户中的钱
		if(presentbalance.longValue() > amount.longValue()){
			result.put("message", "提现金额大于账户余额");
			return false ;
		}
		
		int number = 0 ;
		number = userAccountMapper.updateByPrimaryKeySelective(userAccountNew);
		if(number < 1){
			result.put("message", "数据库查询不到账户信息");
			return false ;
		}
		result.put("message", "提现申请成功");
		return true;
		
	}
	
	
	/**
	 * 当天提现次数
	 * @return
	 * @throws LotterCusException
	 */
	public int withdrawalNum(Long uid) throws LotterCusException{
		int number  = 0  ;
		Date startdate = DateUtil.DateToPattenDate(new Date(), YcContext.DATE_STR_YMD);
		Date nextdate = DateUtil.getDateplusDay(new Date(), 1,null,null,null);
		Date enddate  = DateUtil.DateToPattenDate(nextdate, YcContext.DATE_STR_YMD);
		//不等于失败的提现记录
		number = 	presentCheckMapper.numberTimes(uid, startdate, enddate, PrentCheckStatus.FAILED.getCode());	
		return number ;
	}
	

}
